//
//  KLSGRadioPlayManager.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/11/2.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGRadioPlayManager.h"

@interface KLSGRadioPlayManager ()

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation KLSGRadioPlayManager

#pragma mark - 单例方法实现
+ (KLSGRadioPlayManager *)shareManager
{
    static KLSGRadioPlayManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[[self class] alloc] init];
        manager.player = [[AVPlayer alloc] init];
        manager.player.volume = 1;
    });
    return manager;
}

#pragma mark - 设置播放器URL
- (void)playingWithUrl:(NSString *)url
{
    self.playerItem = nil;
    self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    [self.player replaceCurrentItemWithPlayerItem:_playerItem];
    [self musicPlay];
}

// 开始播放
- (void)musicPlay
{
    if (self.timer != nil) {
        [self.timer invalidate]; // 释放timer
        self.timer = nil;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playingAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    self.isPlaying = YES;
    [self.player play];
}

// 暂停播放
- (void)musicPause
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.isPlaying = NO;
    [self.player pause];
}

// 播放状态切换
- (BOOL)musicPlayOrPause
{
    if (self.isPlaying) {
        [self musicPause];
    } else {
        [self musicPlay];
    }
    return _isPlaying;
}

// slider滑动，设置播放进度方法
- (void)musicSeekToTime:(CGFloat)time
{
    if (self.player.status == AVPlayerStatusReadyToPlay) {
        [self musicPause];
        [self.player seekToTime:CMTimeMakeWithSeconds(time, 1) completionHandler:^(BOOL finished) {
            if (finished) {
                [self musicPlay];
            }
        }];
    }
}

#pragma mark -
- (void)playingAction
{
    dispatch_async(dispatch_get_main_queue(), ^{
        // 获取播放的时间
        if (self.player.currentTime.timescale != 0) {
            CGFloat time = self.player.currentTime.value / self.player.currentTime.timescale;
            if (self.delegate && [self.delegate respondsToSelector:@selector(playingWithProgress:)]) {
                [self.delegate playingWithProgress:time];
            }
        }
    });
}

@end
